package com.yonyou.brigade.third_parties.didi.service.impl;

import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.enums.OpenTypeEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.didi.model.DiDiConfig;
import com.yonyou.brigade.third_parties.didi.service.IDiDiCompanyService;
import com.yonyou.brigade.third_parties.didi.service.IDiDiUserService;
import com.yonyou.brigade.third_parties.didi.util.DiDiConstants;
import com.yonyou.brigade.third_parties.didi.util.DiDiRMIUtils;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DiDiCompanyServiceImpl implements IDiDiCompanyService {

    @Value("${didi.callback}")
    private String didiCallBack;

    @Value("${didi.authIndex}")
    private String authIndex;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    private DiDiRMIUtils diDiRMIUtils;

    @Autowired
    private IDiDiUserService diDiUserService;

    @Autowired
    private IUserCenterService userCenterService;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取授权token
     *
     * @param tenant     租户ID
     * @param tenantName 租户名
     * @param uid        操作人在平台的id，即user_id
     * @return
     */
    @Override
    public String getPlatUrl(String tenant, String tenantName, String uid) {
        Map paramsMap = new HashMap();
        paramsMap.put("out_company_id", tenant);
        paramsMap.put("out_company_name", tenantName);
        paramsMap.put("out_member_id", uid);
        paramsMap.put("auth_scope", "1|2|3");
        paramsMap.put("callback", didiCallBack);
        paramsMap.put(DiDiConstants.KEY_CLIENT_ID, DiDiConstants.PLAT_CLIENT_ID);
        paramsMap.put(DiDiConstants.KEY_CLIENT_SECRET, DiDiConstants.PLAT_CLIENT_SECRET);
        paramsMap.put(DiDiConstants.KEY_TIMESTAMP, System.currentTimeMillis());
        DiDiConfig config = new DiDiConfig();
        config.setClientId(DiDiConstants.PLAT_CLIENT_ID);
        config.setClientSecret(DiDiConstants.PLAT_CLIENT_SECRET);
        config.setSignKey(DiDiConstants.PLAT_SIGNKEY);
        Map<String, Object> companyTokenMap = diDiRMIUtils.keySort(paramsMap, config);
        String sign = diDiRMIUtils.concatRequestParamsAndMd5Encode(companyTokenMap);
        companyTokenMap.put(DiDiConstants.KEY_SIGN, sign);
        String result = diDiRMIUtils.executeRMIRequest(DiDiConstants.METHOD_POST_OPENAUTHTOKEN, companyTokenMap, "POST");
        return result;
    }

    /**
     * 获取自助授权URL
     *
     * @param tenant 租户ID
     * @param phone  管理员手机号
     * @return
     */
    @Override
    public String getAutoAuthUrl(String tenant, String phone) {
        com.alibaba.fastjson.JSONObject tenantInfo = userCenterService.getTenantInfoById(tenant);
        if (tenantInfo == null) {
            throw new CustomException("租户信息查询失败，未查询到租户");
        }
        String tenantName = tenantInfo.getJSONObject("tenant").getString("tenantFullname");
        if (tenantName == null) {
            tenantName = tenantInfo.getJSONObject("tenant").getString("tenantName");
        }

        UcUserDto ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
        if (ucUserDto == null) {
            throw new CustomException("用户信息查询失败，用户中心不存在该用户");
        }
        String tokenResultStr = getPlatUrl(tenant, tenantName, ucUserDto.getUserId());
        JSONObject tokenResult = new JSONObject(tokenResultStr);
        String authToken = "";
        if (0 == tokenResult.optInt("errno") && "SUCCESS".equals(tokenResult.optString("errmsg"))) {
            authToken = tokenResult.optJSONObject("data").optString("open_auth_token");
            /*int authStatus = tokenResult.optJSONObject("data").optInt("auth_status");
            if (0 == authStatus) {
                return authIndex + "?open_auth_token=" + authToken;
            }*/
            return authIndex + "?open_auth_token=" + authToken;
        }
        return null;
    }

    /**
     * 滴滴在线授权开通时回调方法，会将开通信息插入bri_channel表
     *
     * @param params 回调参数参考<link>http://open.es.xiaojukeji.com/doc/erpapi/openAuth/getAuthStatus.html</link>
     * @return Map errno：0表示成功，其它表示失败；errmsg:成功返回"SUCCESS"，失败返回具体错误消息；data：json对象或数组
     */
    @Override
    public Map ddCallBack(Map params) {
        Map result = new HashMap();
        try {
            String type = (String) params.get("type");

            if (type == null){
                result.put("errno", 0);
                result.put("errmsg", "SUCCESS");
                result.put("data", null);
                return result;
            }

            if (type.equals("1")) {
                String tenant = (String) params.get("out_company_id");
                String companyId = (String) params.get("company_id");
                String phone = (String) params.get("phone");
                List<BriChannel> briChannels = briChannelService.getEnableChannelByTenantAndChannel(tenant, ChannelEnum.DIDI.getName());
                if (briChannels != null && briChannels.size() > 0) {
                    //do nothing
                } else {
                    DiDiConfig diDiConfig = new DiDiConfig();
                    diDiConfig.setSignKey(DiDiConstants.PLAT_SIGNKEY);
                    diDiConfig.setClientSecret(DiDiConstants.PLAT_CLIENT_SECRET);
                    diDiConfig.setClientId(DiDiConstants.PLAT_CLIENT_ID);
                    diDiConfig.setCompanyId(companyId);
                    diDiConfig.setPhone(DiDiConstants.PLAT_PHONE);
                    BriChannel briChannel = new BriChannel();
                    briChannel.setPhone(phone);
                    briChannel.setTenant(tenant);
                    briChannel.setConfig(com.alibaba.fastjson.JSONObject.toJSONString(diDiConfig));
                    briChannel.setOpenType(OpenTypeEnum.TENTANT.getIndex());
                    briChannel.setOrgpk("");
                    briChannel.setIsPreApprove(0);
                    briChannel.setEnable(1);
                    briChannel.setChannel(ChannelEnum.DIDI.getName());
                    briChannelService.insert(briChannel);
                    // 异步的同步用户到滴滴
//                    if (BriChannel.NEEDSYNCUSER == briChannel.getNeedSyncUser()) {
                        diDiUserService.syncUsers4Open(tenant, phone);
//                    }
                }
                result.put("errno", 0);
                result.put("errmsg", "SUCCESS");
                result.put("data", null);

            } else {
                result.put("errno", 1);
                result.put("errmsg", "FAIL");
                result.put("data", null);
            }
        } catch (Exception e) {
            result.put("errno", 2);
            result.put("errmsg", "FAIL");
            result.put("data", null);
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 是否已授权租户
     *
     * @param tenant 租户ID
     * @return boolean 是否已授权
     */
    @Override
    public boolean isAuthTenant(String tenant) {
        List<BriChannel> briChannels = briChannelService.getEnableChannelByTenantAndChannel(tenant, ChannelEnum.DIDI.getName());
        return !CollectionUtils.isEmpty(briChannels);
    }
}
